
/* This application is developed by Sameera Bandara
 * this class handles the user location service and displaying notifications
 */







package com.project.visitAll;




import java.io.IOException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;


public class MyService extends Service implements LocationListener{
    private LocationManager locationManager;
	private boolean history;
	private boolean nature;
	private boolean wildLife;
	private boolean sports;
	private boolean rel;
	public static VisitAll MAIN_ACTIVITY;
	private DataHandler dataHandler;
	private Cursor cursor;
	
	
	    public static void setMainActivity(VisitAll activity) 
	    {
	      MAIN_ACTIVITY = activity;      
	    }
	    
	    public IBinder onBind(Intent intent) {
	      return null;
	    }

	    @Override 
	    public void onCreate() {	
	      super.onCreate();
	      locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
	      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
	      startService();
	    }

	    @Override 
	    public void onDestroy() {
	      super.onDestroy();
	      shutdownService();
	    }
	    
	    private void startService(){
	    	this.history=MAIN_ACTIVITY.history;
	    	this.nature=MAIN_ACTIVITY.nature;
	    	this.wildLife=MAIN_ACTIVITY.wildLife;
	    	this.sports=MAIN_ACTIVITY.sports;
	    	this.rel=MAIN_ACTIVITY.rel;
	    	
	    	showToastMessage(this.getString(R.string.start_message));
	    	dataHandler=new DataHandler(this);
	    	dataHandler.open();
	    	
	    	try{
	    		dataHandler.createDatabase();
	    	}catch(IOException e){

	    	}
	    }
	    
	    private void shutdownService(){

	    }

		@Override
		public void onLocationChanged(Location location) {	// if location change, search the database
			Location curruntLocation=location;
			if(curruntLocation.getAccuracy()<1000){
					readDataBase(location);	
				}
		
		}

		@Override
		public void onProviderDisabled(String provider) {
			showToastMessage(this.getString(R.string.GPS_warning));
		}

		@Override
		public void onProviderEnabled(String provider) {
		
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}

		 public float distFrom(double lat1, double lng1, double lat2, double lng2) {    // calculating the distance between two points 
			 double earthRadius = 3958.75;     
			 double dLat = Math.toRadians(lat2-lat1);     
			 double dLng = Math.toRadians(lng2-lng1);     
			 double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2);     
			 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));     
			 double dist = earthRadius * c;      
			 int meterConversion = 1609;      
			 return new Float(dist * meterConversion).floatValue();     
			 } 
		 
		public void showNotification(String tickerTextOne,String contentTitleOne,String contentTextOne,double[] coordiante){	// showing a notification
	    	String ns = Context.NOTIFICATION_SERVICE;
	    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
	    	int icon = R.drawable.android;
	    	CharSequence tickerText =tickerTextOne;
	    	long when = System.currentTimeMillis();
	    	Notification notification = new Notification(icon, tickerText, when);
	    	Context context = getApplicationContext();CharSequence contentTitle = contentTitleOne;
	    	CharSequence contentText = contentTextOne;

	    	Intent notifyIntent = new Intent(this,Map.class);
	    	notifyIntent.putExtra("co",coordiante); //this string is a part of application logic, so don't change it

		    PendingIntent intent = PendingIntent.getActivity(MyService.this, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
	    	notification.setLatestEventInfo(context, contentTitle, contentText, intent);

	    	final int HELLO_ID = 1;
	    	mNotificationManager.notify(HELLO_ID, notification);
	    
		}
		
		public void getUserChoices(boolean history,boolean nature,boolean wildLife,boolean sports,boolean rel){
			this.history=history;
			this.nature=nature;
			this.sports=sports;
			this.wildLife=wildLife;
			this.rel=rel;
		}
		public void readDataBase(Location location){
			if(nature){
				//cursor=dataHandler.getRaws("nature");
				iterator(this.getString(R.string.nature), location);
			}
			if(wildLife){
				//cursor=dataHandler.getRaws("wildLife");
				iterator(this.getString(R.string.wild_life), location);
			}
			if(sports){
				//cursor=dataHandler.getRaws("sports");
				iterator(this.getString(R.string.sports),location);
			}
			if(history){
				//cursor=dataHandler.getRaws("history");
				iterator(this.getString(R.string.history), location);
			}
			if(rel){
				//cursor=dataHandler.getRaws("rel");
				iterator(this.getString(R.string.religion), location);
			}
		}
		public void iterator(String type,Location location){		//itertor for read the database queries
			 cursor=dataHandler.getRaws(type);
			 cursor.moveToNext();
			boolean fa;
			do{
				float dis=distFrom(location.getLatitude(), location.getLongitude(),cursor.getDouble(1), cursor.getDouble(2));
				if(dis<5000){
					
					double[] coordinates=new double[2];
					coordinates[0]=cursor.getDouble(1);
					coordinates[1]=cursor.getDouble(2);
					showNotification(this.getString(R.string.app_name),cursor.getString(0),this.getString(R.string.distance)+(Math.round(dis/1000))+this.getString(R.string.unit_Kms)+this.getString(R.string.click_message),coordinates);
					
				}
				fa=cursor.moveToNext();
			}while(fa);
		}
		public void showToastMessage(String msg){
        	Context context = getApplicationContext();
        	int duration = Toast.LENGTH_LONG;
        	Toast toast = Toast.makeText(context, msg, duration);
        	toast.show();
		}

		

}
